#include "chatserver.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QTextEdit>
#include <QPushButton>
#include <QLabel>
#include <QSpinBox>
#include <QMessageBox>
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QApplication>
#include <QStyle>

ChatServer::ChatServer(QWidget *parent)
    : QWidget(parent)
    , udpSocket(nullptr)
    , database(new Database(this))
    , isRunning(false)
    , serverPort(8888)
{
    // 初始化数据库
    if (!database->initDatabase()) {
        QMessageBox::warning(this, "警告", "数据库初始化失败！");
    }
    
    // 设置界面
    setupUI();
    
    // 设置窗口属性
    setWindowTitle("聊天服务器 - Qt网络聊天程序");
    setMinimumSize(600, 500);
    
    // 应用样式
    setStyleSheet(R"(
        QWidget {
            background-color: #f0f0f0;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        QTextEdit {
            background-color: white;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 5px;
            font-size: 12px;
        }
        QPushButton {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            font-size: 12px;
            min-width: 80px;
        }
        QPushButton:hover {
            background-color: #45a049;
        }
        QPushButton:pressed {
            background-color: #3d8b40;
        }
        QPushButton:disabled {
            background-color: #cccccc;
        }
        QLabel {
            color: #333;
            font-weight: bold;
        }
        QSpinBox {
            border: 1px solid #ccc;
            border-radius: 3px;
            padding: 3px;
        }
    )");
}

ChatServer::~ChatServer()
{
    if (udpSocket) {
        udpSocket->close();
        delete udpSocket;
    }
}

void ChatServer::setupUI()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 创建标题
    QLabel *titleLabel = new QLabel("聊天服务器控制台");
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 18px; color: #2c3e50; margin: 10px;");
    mainLayout->addWidget(titleLabel);
    
    // 创建控制面板
    QHBoxLayout *controlLayout = new QHBoxLayout();
    
    QLabel *portLabel = new QLabel("端口:");
    portSpinBox = new QSpinBox();
    portSpinBox->setRange(1024, 65535);
    portSpinBox->setValue(serverPort);
    portSpinBox->setFixedWidth(100);
    
    startButton = new QPushButton("启动服务器");
    stopButton = new QPushButton("停止服务器");
    stopButton->setEnabled(false);
    
    controlLayout->addWidget(portLabel);
    controlLayout->addWidget(portSpinBox);
    controlLayout->addWidget(startButton);
    controlLayout->addWidget(stopButton);
    controlLayout->addStretch();
    
    mainLayout->addLayout(controlLayout);
    
    // 创建状态显示
    statusLabel = new QLabel("服务器状态: 未启动");
    statusLabel->setStyleSheet("color: #e74c3c; font-weight: bold;");
    mainLayout->addWidget(statusLabel);
    
    // 创建分割布局
    QHBoxLayout *contentLayout = new QHBoxLayout();
    
    // 左侧：聊天记录显示
    QVBoxLayout *chatLayout = new QVBoxLayout();
    QLabel *chatLabel = new QLabel("聊天记录:");
    chatTextEdit = new QTextEdit();
    chatTextEdit->setReadOnly(true);
    chatTextEdit->setMaximumHeight(300);
    
    QHBoxLayout *chatButtonLayout = new QHBoxLayout();
    historyButton = new QPushButton("加载历史");
    clearButton = new QPushButton("清空记录");
    chatButtonLayout->addWidget(historyButton);
    chatButtonLayout->addWidget(clearButton);
    chatButtonLayout->addStretch();
    
    chatLayout->addWidget(chatLabel);
    chatLayout->addWidget(chatTextEdit);
    chatLayout->addLayout(chatButtonLayout);
    
    // 右侧：服务器日志
    QVBoxLayout *logLayout = new QVBoxLayout();
    QLabel *logLabel = new QLabel("服务器日志:");
    logTextEdit = new QTextEdit();
    logTextEdit->setReadOnly(true);
    logTextEdit->setMaximumHeight(300);
    
    logLayout->addWidget(logLabel);
    logLayout->addWidget(logTextEdit);
    
    contentLayout->addLayout(chatLayout);
    contentLayout->addLayout(logLayout);
    
    mainLayout->addLayout(contentLayout);
    
    // 连接信号和槽
    connect(startButton, &QPushButton::clicked, this, &ChatServer::startServer);
    connect(stopButton, &QPushButton::clicked, this, &ChatServer::stopServer);
    connect(clearButton, &QPushButton::clicked, this, &ChatServer::clearHistory);
    connect(historyButton, &QPushButton::clicked, this, &ChatServer::loadHistory);
}

void ChatServer::startServer()
{
    if (isRunning) {
        return;
    }
    
    serverPort = portSpinBox->value();
    
    // 创建UDP套接字
    udpSocket = new QUdpSocket(this);
    
    // 绑定端口
    if (!udpSocket->bind(QHostAddress::Any, serverPort)) {
        QMessageBox::critical(this, "错误", "无法绑定端口 " + QString::number(serverPort));
        return;
    }
    
    // 连接信号
    connect(udpSocket, &QUdpSocket::readyRead, this, &ChatServer::handleReadyRead);
    
    isRunning = true;
    startButton->setEnabled(false);
    stopButton->setEnabled(true);
    portSpinBox->setEnabled(false);
    
    statusLabel->setText("服务器状态: 运行中 (端口: " + QString::number(serverPort) + ")");
    statusLabel->setStyleSheet("color: #27ae60; font-weight: bold;");
    
    addLog("服务器启动成功，监听端口: " + QString::number(serverPort));
}

void ChatServer::stopServer()
{
    if (!isRunning) {
        return;
    }
    
    if (udpSocket) {
        udpSocket->close();
        delete udpSocket;
        udpSocket = nullptr;
    }
    
    // 清空客户端列表
    QMutexLocker locker(&clientsMutex);
    clients.clear();
    
    isRunning = false;
    startButton->setEnabled(true);
    stopButton->setEnabled(false);
    portSpinBox->setEnabled(true);
    
    statusLabel->setText("服务器状态: 已停止");
    statusLabel->setStyleSheet("color: #e74c3c; font-weight: bold;");
    
    addLog("服务器已停止");
}

void ChatServer::handleReadyRead()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress senderAddr;
        quint16 senderPort;
        
        udpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddr, &senderPort);
        
        // 解析JSON消息
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(datagram, &error);
        
        if (error.error != QJsonParseError::NoError) {
            addLog("收到无效消息格式: " + error.errorString());
            continue;
        }
        
        QJsonObject jsonObj = doc.object();
        QString type = jsonObj["type"].toString();
        
        if (type == "connect") {
            // 新客户端连接
            QString clientName = jsonObj["name"].toString();
            
            QMutexLocker locker(&clientsMutex);
            clients.append(qMakePair(senderAddr, senderPort));
            
            addLog("新客户端连接: " + clientName + " (" + senderAddr.toString() + ":" + QString::number(senderPort) + ")");
            
            // 发送连接确认
            QJsonObject response;
            response["type"] = "connect_ack";
            response["message"] = "连接成功";
            
            QJsonDocument responseDoc(response);
            udpSocket->writeDatagram(responseDoc.toJson(), senderAddr, senderPort);
            
        } else if (type == "message") {
            // 聊天消息
            QString sender = jsonObj["sender"].toString();
            QString message = jsonObj["message"].toString();
            QString timestamp = getCurrentTimestamp();
            
            // 保存到数据库
            database->saveMessage(sender, message, timestamp);
            
            // 显示消息
            QString displayMsg = QString("[%1] %2: %3").arg(timestamp).arg(sender).arg(message);
            chatTextEdit->append(displayMsg);
            
            addLog("收到消息: " + sender + " -> " + message);
            
            // 广播给所有客户端
            broadcastMessage(message, senderAddr, senderPort);
        }
    }
}

void ChatServer::broadcastMessage(const QString &message, const QHostAddress &senderAddr, quint16 senderPort)
{
    QJsonObject broadcastMsg;
    broadcastMsg["type"] = "broadcast";
    broadcastMsg["message"] = message;
    broadcastMsg["timestamp"] = getCurrentTimestamp();
    
    QJsonDocument doc(broadcastMsg);
    QByteArray data = doc.toJson();
    
    QMutexLocker locker(&clientsMutex);
    for (const auto &client : clients) {
        // 不发送给消息发送者
        if (client.first != senderAddr || client.second != senderPort) {
            udpSocket->writeDatagram(data, client.first, client.second);
        }
    }
}

void ChatServer::clearHistory()
{
    if (database->clearHistory()) {
        chatTextEdit->clear();
        addLog("聊天记录已清空");
    } else {
        addLog("清空聊天记录失败");
    }
}

void ChatServer::loadHistory()
{
    QStringList history = database->loadHistory(50);
    chatTextEdit->clear();
    
    for (const QString &msg : history) {
        chatTextEdit->append(msg);
    }
    
    addLog("已加载 " + QString::number(history.size()) + " 条历史记录");
}

void ChatServer::addLog(const QString &message)
{
    QString timestamp = getCurrentTimestamp();
    QString logMsg = QString("[%1] %2").arg(timestamp).arg(message);
    logTextEdit->append(logMsg);
}

QString ChatServer::getCurrentTimestamp()
{
    return QDateTime::currentDateTime().toString("hh:mm:ss");
}
